<?php

namespace app\common\model;

class CourseAdjust extends \think\Model
{
    const ADJUST_CACHE = "CourseAdjustCache";
    const ADJUST_EXPIRE = 3600 * 10;

    protected $pk="from_date";
    protected $cache;

    public function setStatusAttr($value)
    {
        return $value ? 1 : 0;
    }

    public function getStatusAttr($value)
    {
        return !!$value;
    }

    public static function clearCache(){
        cache(CourseAdjust::ADJUST_CACHE, null);
    }
    

    /**
     * 建立缓存
     *
     * @return array
     */
    public static function getCache()
    {
        if (!($cache = cache(CourseAdjust::ADJUST_CACHE))) {
            $result = CourseAdjust::where('status', '1')->order('from_date')->select();
            $cache = [];
            foreach ($result as $v) {
                $toDate = $v['to_date'];
                $fromDate = $v['from_date'];
                if (isset($cache[$fromDate])) {
                    $cache[$toDate] = $cache[$fromDate];
                } else {
                    $cache[$toDate] = $fromDate;
                }
                $cache[$fromDate] = false;
            }
            cache(CourseAdjust::ADJUST_CACHE, $cache, CourseAdjust::ADJUST_EXPIRE);
        }
        return $cache;
    }

    /**
     * 将一个字符串类型的日期转换为相应的DateTime对象,同时进行时间的转换
     *
     * @param [type] $oldDate
     * @return string
     */
    public function getDate($oldDate = null)
    {
        if (!isset($this->cache)) {
            $this->cache = CourseAdjust::getCache();
        }
        if (is_string($oldDate)) {
            $date = strtotime(($oldDate));
        } else if (is_subclass_of($oldDate, 'DateTime', false)) {
            $date = $oldDate->getTimeStamp();
        } else if (is_int($oldDate)) {
            $date = time($oldDate);
        } else {
            $date = time();
        }
        $dateStr = date("Y-m-d", $date);

        if (isset($this->cache[$dateStr])) {
            return $this->cache[$dateStr];
        } else {
            return $dateStr;
        }
    }
}
